<template>
  <div>
    <div class="eq_803">
      <el-row :gutter="20">
        <!-- 字段组 1：选择SIDE -->
        <el-col :xs="24" :sm="24" :md="12">
          <el-row :gutter="10" align="middle">
            <el-col :span="8">
              <label class="tny-tt">买/卖</label>
            </el-col>
            <el-col :span="16">
              <el-select class="tny-tcs" size="mini" v-model="orderQueryParams.trd_side" placeholder="请选择SIDE"
                         clearable
              >
                <el-option
                    v-for="(side) in trdSideOption"
                    v-if="side.value !== 'NONE'"
                    :key="side.value"
                    :label="side.label_operate"
                    :value="side.value"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-col>

        <!-- 字段组 2：选择账户 -->
        <el-col :xs="24" :sm="24" :md="12">
          <el-row :gutter="10" align="middle">
            <el-col :span="8">
              <label class="tny-tt">{{ fund_info && fund_info.acc_id ? '当前' : '选择' }}账户</label>
            </el-col>
            <el-col :span="16">
              <div v-if="fund_info && fund_info.acc_id" class="tny-tcs" style="line-height: 28px;">
                <el-tag size="mini" type="primary" style="text-transform: uppercase;">
                  {{ fund_info.user_name || '未知账户' }}
                </el-tag>
              </div>
              <el-select
                  v-else
                  class="tny-tcs"
                  :disabled="funds_list.length === 0"
                  :loading="funds_list.length === 0"
                  size="mini"
                  v-model="orderQueryParams.acc_id"
                  placeholder="请选择账户"
                  clearable
              >
                <el-option
                    v-for="(user) in funds_list"
                    :key="user.trd_account"
                    :label="user.user_name || '未命名账户'"
                    :value="user.trd_account"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-col>

        <!-- 字段组 3：选择状态 -->
        <el-col :xs="24" :sm="24" :md="12">
          <el-row :gutter="10" align="middle">
            <el-col :span="8">
              <label class="tny-tt">选择状态</label>
            </el-col>
            <el-col :span="16">
              <el-select class="tny-tcs" size="mini" v-model="orderQueryParams.order_status" placeholder="请选择状态"
                         clearable
              >
                <el-option
                    v-for="(status) in trdOrderStatusOption"
                    :key="status.value"
                    :label="status.label"
                    :value="status.value"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-col>
        <!-- 字段组 4：市场 -->
        <el-col :xs="24" :sm="24" :md="12">
          <el-row :gutter="10" align="middle">
            <el-col :span="8">
              <label class="tny-tt">选择市场</label>
            </el-col>
            <el-col :span="16">
              <el-select class="tny-tcs" size="mini" v-model="orderQueryParams.market_name" placeholder="请选择市场"
                         clearable
              >
                <el-option
                    v-for="(market) in marketList"
                    :key="market.value"
                    :label="market.text"
                    :value="market.value"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-col>
        <!-- 字段组 5：操作按钮 -->
        <el-col :xs="24" :sm="24" :md="12">
          <el-row :gutter="10" align="middle">
            <el-col :span="16" :offset=8>
              <el-button size="mini" type="primary" @click="handleQuery">查询</el-button>
              <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>
    <div v-if="loading_trd_order" class="blank_skeleton">
      <el-skeleton :rows="4" animated/>
    </div>
    <el-table
        v-else
        border
        size="mini"
        height="600px"
        :data="recent_orders"
        style="width: 100%;"
    >
      <el-table-column label="SIDE" width="80px" fixed>
        <template v-slot="scope">
          <div style="display: flex; justify-content: center; flex-direction: column;">
            <div :style="{color:scope.row.label_operate_color, fontSize: '14px'}">
              {{ scope.row.label_operate_tip }}
            </div>
            <div
                style="display: flex; color: #424242; font-size: 10px; align-content: center; align-items: center; gap:4px;"
            >
              <el-image
                  v-if="scope.row.order_status_icon"
                  :src="scope.row.order_status_icon"
                  mode="aspectFill"
                  style="width: 12px; height: 12px;"
              />
              {{ scope.row.order_status_tip }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column width="140px">
        <template v-slot:header>
          <div class="eq_tbhd_txf_00">
            <div>账户</div>
            <div class="eq_tbhd_txf_01">北京时间</div>
          </div>
        </template>
        <template v-slot="scope">
          <div class="eq_tbhd_txf_02 ellipsis">
            <div v-if="scope.row.acc_name" @click="gotoAccIndex(scope.row)" class="tny-4c30">{{
                scope.row.acc_name
              }}
            </div>
            <div v-else style="font-size: 10px; color: #bbb">未知账户</div>
          </div>
          <div class="eq_tbhd_txf_03 ellipsis">
            {{ formatSmartTime(scope.row.createTimestamp) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column width="120px">
        <template v-slot:header>
          <div class="eq_tbhd_txf_00">
            <div>STOCK</div>
            <div class="eq_tbhd_txf_01">CODE</div>
          </div>

        </template>
        <template v-slot="scope">
          <div @click="openXq(scope.row.code)" class="xq-lnk">
            <div class="eq_tbhd_txf_02 ellipsis">{{ scope.row.stock_name }}</div>
            <StockCodeFlag :stock-code="scope.row.code"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column>
        <template v-slot:header>
          <div class="eq_tbhd_txf_00">
            <div>出价</div>
            <div class="eq_tbhd_txf_01">成交价</div>
          </div>
        </template>
        <template v-slot="scope">
          <div class="eq_tbhd_txf_02 ellipsis">{{ scope.row.price }}</div>
          <div
              v-if="scope.row.dealt_avg_price === scope.row.price"
              class="eq_tbhd_txf_03 ellipsis"
          >{{ scope.row.price }}
          </div>
          <div
              v-else
              class="eq_tbhd_txf_03 ellipsis"
          >{{ scope.row.dealt_avg_price > 0 ? scope.row.dealt_avg_price : '未成交' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column>
        <template v-slot:header>
          <div class="eq_tbhd_txf_00">
            <div>数量</div>
            <div class="eq_tbhd_txf_01">成交数</div>
          </div>
        </template>
        <template v-slot="scope">
          <div class="eq_tbhd_txf_02 ellipsis">{{ scope.row.qty }}</div>
          <div class="eq_tbhd_txf_03 ellipsis">
            {{ scope.row.dealt_qty > 0 ? scope.row.dealt_qty : '未成交' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column>
        <template v-slot:header>
          <div class="eq_tbhd_txf_00">
            <div>市值</div>
            <div class="eq_tbhd_txf_01">成交市值</div>
          </div>
        </template>
        <template v-slot="scope">
          <div class="eq_tbhd_txf_02 ellipsis">{{ scope.row.market_val_fmt }}
            <span class="eq_tbhd_txf_04">{{ scope.row.currency }}</span>
          </div>
          <div class="eq_tbhd_txf_03 ellipsis">
            {{ scope.row.dealt_val ? scope.row.dealt_val_fmt : '未成交' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column>
        <template v-slot:header>
          <div class="eq_tbhd_txf_00">
            <div>占比</div>
          </div>
        </template>
        <template v-slot="scope">
          <div class="eq_tbhd_txf_02 ellipsis">{{ scope.row.trading_ratio }}</div>
          <div class="eq_tbhd_txf_03 ellipsis">
            {{ scope.row.trd_side === 'SELL' ? '占持仓' : scope.row.trd_side === 'BUY' ? '占总资产' : '' }}
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="orderQueryParams.page"
        :page-size="orderQueryParams.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="orderQueryParams.total"
    />
  </div>
</template>

<script>
import { getTrdOrderList } from '@/api/dashboard'
import StockCodeFlag from '@/components/ItemRow/StockCodeFlag'

export default {
  name: 'PlaceOrderList',
  props: {
    funds_list: {
      type: Array,
      default: () => []
    },
    fund_info: {
      type: Object,
      default: () => ({})
    }
  },
  components: {
    StockCodeFlag
  },
  data() {
    return {
      marketIcon: '',
      trdSideOption: this.hashmap.trdSideOption,
      trdOrderStatusOption: this.hashmap.trdOrderStatusOption,
      trdOrderTypeOption: this.hashmap.trdOrderTypeOption,
      marketList: this.hashmap.marketList,
      recent_orders: [],
      loading_trd_order: false,

      orderQueryParams: {
        page: 1,
        page_size: 50,
        trd_side: null,
        order_status: null,
        acc_id: null,
        market_name: null,
        total: 0
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    if (this.fund_info && this.fund_info.acc_id) {
      this.orderQueryParams.acc_id = this.fund_info.acc_id
    }
    this.loadOrder()
  },
  methods: {
    loadOrder() {
      this.loading_trd_order = true
      getTrdOrderList({
        // rid: 10078,
        // token: 'd078e8b5f3a3a4a2',
        ...this.orderQueryParams
      }).then(({ code, data }) => {
        this.recent_orders = []
        if (code === 0 && data?.list?.length) {
          this.recent_orders = data.list.map(row => {
            const normalized = this.normalizeRowNumbers(row, ['trd_account'])
            const order_type_tip = this.findJsonByKeyValue(this.trdOrderTypeOption, 'value', normalized.order_type)?.label || ''
            const order_status_tip = this.findJsonByKeyValue(this.trdOrderStatusOption, 'value', normalized.order_status)?.label || ''
            const order_status_icon = this.findJsonByKeyValue(this.trdOrderStatusOption, 'value', normalized.order_status)?.icon || ''
            const label_operate_tip = this.findJsonByKeyValue(this.trdSideOption, 'value', normalized.trd_side).label_operate
            const label_operate_color = this.findJsonByKeyValue(this.trdSideOption, 'value', normalized.trd_side).color
            const market_val = normalized.qty * normalized.price
            const market_val_fmt = market_val.toLocaleString('en-US', {
              minimumFractionDigits: 0,
              maximumFractionDigits: 2
            })
            const dealt_val = normalized.dealt_qty * normalized.dealt_avg_price
            const dealt_val_fmt = dealt_val.toLocaleString('en-US', {
              minimumFractionDigits: 0,
              maximumFractionDigits: 2
            })
            return {
              ...normalized,
              order_type_tip,
              order_status_tip,
              order_status_icon,
              label_operate_tip,
              label_operate_color,
              market_val,
              market_val_fmt,
              dealt_val,
              dealt_val_fmt
            }
          })
          this.orderQueryParams.total = data.total
        }
      }).finally(() => {
        this.loading_trd_order = false
      })
    },
    gotoAccIndex(acc) {
      this.$router.push({
        path: `/acc/index?trd_account=${acc.trd_account}`
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.orderQueryParams.page = 1
      this.loadOrder()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$router.replace({ query: {} }) // 清除 URL 参数
      delete this.orderQueryParams.acc_id
      delete this.orderQueryParams.order_status
      delete this.orderQueryParams.market_name
      delete this.orderQueryParams.trd_side
      this.orderQueryParams.page = 1
      this.loadOrder()
    },
    handleSizeChange(val) {
      this.orderQueryParams.page_size = val
      this.loadOrder()
    },
    handleCurrentChange(val) {
      this.orderQueryParams.page = val
      this.loadOrder()
    }
  }
}

</script>
<style>
.tny-tt {
  font-size: 14px;
  font-weight: bold;
  line-height: 28px;
}

.tny-tcs {
  margin-bottom: 10px;
}
</style>
